package com.fanyue.modules.wzb.service.impl;

import cn.hutool.core.lang.Dict;
import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.digest.MD5;
import cn.hutool.json.JSON;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.fanyue.core.base.BaseServiceImpl;
import com.fanyue.core.cache.CoolCache;
import com.fanyue.core.exception.CoolPreconditions;
import com.fanyue.core.request.R;
import com.fanyue.core.util.CoolSecurityUtil;
import com.fanyue.core.util.DatabaseDialectUtils;
import com.fanyue.modules.base.entity.sys.BaseSysDepartmentEntity;
import com.fanyue.modules.base.entity.sys.BaseSysRoleEntity;
import com.fanyue.modules.base.entity.sys.BaseSysUserEntity;
import com.fanyue.modules.base.service.sys.BaseSysDepartmentService;
import com.fanyue.modules.wzb.entity.AppUserEntity;
import com.fanyue.modules.wzb.entity.ClothingSpecEntity;
import com.fanyue.modules.wzb.mapper.AppUserMapper;
import com.fanyue.modules.wzb.service.AppUserService;
import com.fanyue.modules.wzb.service.ClothingSpecService;
import com.fanyue.modules.wzb.utils.FaceApiUtils;
import com.fanyue.modules.wzb.vo.AppUserImportVO;
import com.mybatisflex.core.paginate.Page;
import com.mybatisflex.core.query.QueryWrapper;
import com.mybatisflex.core.update.UpdateChain;
import com.tangzc.autotable.core.constants.DatabaseDialect;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.fanyue.modules.base.entity.sys.table.BaseSysDepartmentEntityTableDef.BASE_SYS_DEPARTMENT_ENTITY;
import static com.fanyue.modules.wzb.entity.table.AppUserEntityTableDef.APP_USER_ENTITY;


/**
 * 系统用户
 */
@Service
@RequiredArgsConstructor
public class AppUserServiceImpl extends BaseServiceImpl<AppUserMapper, AppUserEntity> implements AppUserService {

    final private CoolCache coolCache;
    final private BaseSysDepartmentService sysDepartmentService;
    final private ClothingSpecService clothingSpecService;

    @Override
    public Object page(JSONObject requestParams, Page<AppUserEntity> page, QueryWrapper qw) {
        String uidType = requestParams.getStr("uidType");
        String keyWord = requestParams.getStr("keyWord");
        Integer status = requestParams.getInt("status");
        Integer sex = requestParams.getInt("sex");
        Long[] departmentIds = requestParams.get("departmentIds", Long[].class);
        JSONObject tokenInfo = CoolSecurityUtil.getAdminUserInfo(requestParams);
        // 用户的部门权限
        Long[] permsDepartmentArr = coolCache.get("admin:department:" + tokenInfo.get("userId"),
                Long[].class);
        String databaseDialect = DatabaseDialectUtils.getDatabaseDialect();
        if (databaseDialect.equals(DatabaseDialect.PostgreSQL)) {
            // 兼容postgresql
            qw.select("base_sys_department.name AS departmentName");
        } else {
            qw.select(APP_USER_ENTITY.ALL_COLUMNS,BASE_SYS_DEPARTMENT_ENTITY.NAME.as("departmentName"));
        }

        qw.from(APP_USER_ENTITY)
                .leftJoin(BASE_SYS_DEPARTMENT_ENTITY)
                .on(APP_USER_ENTITY.DEPARTMENT_ID.eq(BASE_SYS_DEPARTMENT_ENTITY.ID));

        // 筛选部门
        qw.and(APP_USER_ENTITY.DEPARTMENT_ID.in(departmentIds,
                ArrayUtil.isNotEmpty(departmentIds)));
        // 筛选状态
        qw.and(APP_USER_ENTITY.STATUS.eq(status, status != null));
        qw.and(APP_USER_ENTITY.SEX.eq(sex, sex != null));
        // 搜索关键字
        if (StrUtil.isNotEmpty(keyWord)) {
            qw.and(APP_USER_ENTITY.NAME.like(keyWord)
                    .or(APP_USER_ENTITY.MOBILE.like(keyWord))
                    .or(APP_USER_ENTITY.UID.like(keyWord)));
        }
        // 过滤部门权限
        qw.and(APP_USER_ENTITY.DEPARTMENT_ID.in(
                permsDepartmentArr == null || permsDepartmentArr.length == 0 ? new Long[]{null}
                        : permsDepartmentArr,
                !CoolSecurityUtil.getAdminUsername().equals("admin")));
        if (databaseDialect.equals(DatabaseDialect.PostgreSQL)) {
            // 兼容postgresql
            qw.groupBy("base_sys_department.name");
        } else {
            qw.groupBy(APP_USER_ENTITY.ID);
        }
        Page<AppUserEntity> page1 = mapper.paginate(page, qw);
        List<AppUserEntity> list = page1.getRecords();
        for (AppUserEntity appUser: list) {
            if (StrUtil.isNotEmpty(appUser.getSpecData())) {
                JSONObject jsonObject = new JSONObject(appUser.getSpecData());
                appUser.setSpec1(jsonObject.getLong("spec1"));
                appUser.setSpec2(jsonObject.getLong("spec2"));
                appUser.setSpec3(jsonObject.getLong("spec3"));
                appUser.setSpec4(jsonObject.getLong("spec4"));
            }
        }
        if (ObjectUtil.isNotEmpty(uidType) && uidType.equals("1")) {
            for (AppUserEntity appUser: list) {
                String uid1 = "";
                //显示后六位
                if (appUser.getUid() != null) {
                    if (appUser.getUid().length() > 6) {
                        int length = appUser.getUid().length();
                        uid1 = appUser.getUid().substring(length - 6);
                    } else {
                        uid1 = appUser.getUid();
                    }
                }
                appUser.setUid(uid1);
            }
        }
        return page1;
    }

    @Override
    public Long add(JSONObject requestParams, AppUserEntity entity) {
        if (StrUtil.isNotEmpty(entity.getUid())) {
            AppUserEntity check = getOne(
                    QueryWrapper.create().eq(AppUserEntity::getUid, entity.getUid()));
            CoolPreconditions.check(check != null, "用户证件号已存在");
        }
        Map<String, Object> map = new HashMap<>();
        map.put("spec1", entity.getSpec1());
        map.put("spec2", entity.getSpec2());
        map.put("spec3", entity.getSpec3());
        map.put("spec4", entity.getSpec4());
        entity.setSpecData(JSONUtil.toJsonStr(map));
        super.add(requestParams, entity);
        return entity.getId();
    }

    @Override
    public boolean update(JSONObject requestParams, AppUserEntity entity) {
        if (StrUtil.isNotEmpty(entity.getUid())) {
            AppUserEntity check = getOne(
                    QueryWrapper.create().eq(AppUserEntity::getUid, entity.getUid())
                            .ne(AppUserEntity::getId, entity.getId()));
            CoolPreconditions.check(check != null, "用户编号已存在");
        }
        Map<String, Object> map = new HashMap<>();
        map.put("spec1", entity.getSpec1());
        map.put("spec2", entity.getSpec2());
        map.put("spec3", entity.getSpec3());
        map.put("spec4", entity.getSpec4());
        entity.setSpecData(JSONUtil.toJsonStr(map));
        return super.update(requestParams, entity);
    }

    @Override
    public Object list(JSONObject requestParams, QueryWrapper queryWrapper) {
        //Integer type = requestParams.getInt("type");
        Long departmentId = requestParams.getLong("departmentId");
        String uid = requestParams.getStr("uid");
        String name = requestParams.getStr("name");
        queryWrapper.from(APP_USER_ENTITY);
       /* if (type != null) {
            queryWrapper.and(APP_USER_ENTITY.TYPE.eq(type));
        }*/
        if (departmentId != null) {
            queryWrapper.and(APP_USER_ENTITY.DEPARTMENT_ID.eq(departmentId));
        }
        if (StrUtil.isNotEmpty(uid)) {
            queryWrapper.and(APP_USER_ENTITY.UID.like(uid));
        }
        if (StrUtil.isNotEmpty(name)) {
            queryWrapper.and(APP_USER_ENTITY.NAME.like(name));
        }
        List<AppUserEntity> list = mapper.selectListByQuery(queryWrapper);
        for (AppUserEntity appUser: list) {
            String uid1 = "";
            //显示后六位
            if (appUser.getUid() != null) {
                if (appUser.getUid().length() > 6) {
                    int length = appUser.getUid().length();
                    uid1 = appUser.getUid().substring(length - 6);
                } else {
                    uid1 = appUser.getUid();
                }
            }
            appUser.setUid(uid1);
        }
        return list;
    }
    @Override
    public Object info(Long id) {
        AppUserEntity appUser = getById(id);
        if (StrUtil.isNotEmpty(appUser.getSpecData())) {
            JSONObject jsonObject = new JSONObject(appUser.getSpecData());
            appUser.setSpec1(jsonObject.getLong("spec1"));
            appUser.setSpec2(jsonObject.getLong("spec2"));
            appUser.setSpec3(jsonObject.getLong("spec3"));
            appUser.setSpec4(jsonObject.getLong("spec4"));
        }
        return appUser;
    }

    @Override
    public boolean delete(JSONObject requestParams, Long... ids) {
        super.delete(ids);
        for (Long id:ids) {
            Map<String,Object> param = new HashMap<>();
            param.put("userId", id);
            try {
                FaceApiUtils.delete(param);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return false;
    }

    @Override
    public List<AppUserEntity> listByInfo(AppUserEntity info) {
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.select(APP_USER_ENTITY.ALL_COLUMNS);
        queryWrapper.from(APP_USER_ENTITY);
        /*// 用户的部门权限
        Long[] permsDepartmentArr = info.getDepartmentIds();

        if (permsDepartmentArr != null && permsDepartmentArr.length > 0) {
            queryWrapper.and(APP_USER_ENTITY.DEPARTMENT_ID.in(
                    permsDepartmentArr,
                    !CoolSecurityUtil.getAdminUsername().equals("admin")));
            queryWrapper.groupBy(APP_USER_ENTITY.ID);
        }*/

        queryWrapper.and(APP_USER_ENTITY.STATUS.eq(info.getStatus(), info.getStatus() != null));
        queryWrapper.and(APP_USER_ENTITY.UID.eq(info.getUid(), StrUtil.isNotEmpty(info.getUid())));
        if (info.getFaceId() != null && info.getFaceId().equals(0L)) {
            queryWrapper.and(APP_USER_ENTITY.HEAD_IMAGE.isNotNull());
            queryWrapper.and(APP_USER_ENTITY.HEAD_IMAGE.ne(""));
        }

        queryWrapper.orderBy(APP_USER_ENTITY.UPDATE_TIME.asc());
        return mapper.selectListByQuery(queryWrapper);
    }

    @Override
    public R importSave(List<AppUserImportVO> importVOList) {
        List<AppUserEntity> appUserList = new ArrayList<>();
        List<BaseSysDepartmentEntity> departmentList = sysDepartmentService.allList();
        List<ClothingSpecEntity> specList = clothingSpecService.listByInfo(new ClothingSpecEntity());

        for (AppUserImportVO importVO: importVOList) {
            AppUserEntity appUserEntity = new AppUserEntity();
            //基本数据
            appUserEntity.setName(importVO.getName());
            appUserEntity.setUid(importVO.getUid());
            appUserEntity.setMobile(importVO.getMobile());
            int sex = 0;
            if (importVO.getSex().equals("男")) sex = 1;
            if (importVO.getSex().equals("女")) sex = 2;
            appUserEntity.setSex(sex);
            //型号
            Map<String, Object> map = new HashMap<>();
            map.put("spec1", getSpecId(specList, importVO.getSpec1(), 1));
            map.put("spec2", getSpecId(specList, importVO.getSpec2(), 2));
            map.put("spec3", getSpecId(specList, importVO.getSpec3(), 3));
            map.put("spec4", getSpecId(specList, importVO.getSpec4(), 4));
            appUserEntity.setSpecData(JSONUtil.toJsonStr(map));
            //机构
            String[] departments = importVO.getDepartment().split("/");
            BaseSysDepartmentEntity dept = getDept(departmentList, departments[departments.length - 1]);
            if (ObjectUtil.isNotEmpty(dept)) {
                appUserEntity.setDepartmentId(dept.getId());
                appUserEntity.setDepartmentName(dept.getName());
            }
            //添加
            appUserList.add(appUserEntity);
        }
        this.saveBatch(appUserList);
        return R.ok();
    }

    private static Long getSpecId(
            List<ClothingSpecEntity> specList,
            String name,
            Integer category) {
        for (ClothingSpecEntity specEntity: specList) {
            if (specEntity.getCategory().equals(category) && specEntity.getName().equals(name)) {
                return specEntity.getId();
            }
        }
        return -1L;
    }
    private static BaseSysDepartmentEntity getDept(
            List<BaseSysDepartmentEntity> list,
            String name) {
        for (BaseSysDepartmentEntity info: list) {
            if (info.getName().equals(name)) {
                return info;
            }
        }
        return new BaseSysDepartmentEntity();
    }
}